package backtrack;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author way
 * @create 2025-02-19 21:26
 */
public class _216_combinationSum3 {
    List<List<Integer>> res = new ArrayList<>();
    LinkedList<Integer> path = new LinkedList<>();

    public List<List<Integer>> combinationSum3(int k, int n) {
        dfs(k, n, 1, 0);
        return res;
    }

    private void dfs(int k, int n, int startIndex, int sum) {
        if (sum > n) return;

        if (path.size() > k) return;

        if (sum == n && path.size() == k) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i <= 9; i++) {
            path.add(i);
            sum += i;
            dfs(k, n, i + 1, sum);
            sum -= i;
            path.removeLast();
        }
    }
}
